#include "destroyball.h"
#include "ui_destroyball.h"

#include <QMessageBox>

destroyball::destroyball(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::destroyball)
{
    ui->setupUi(this);

    // 初始状态下 小球的个数
    m_startBallCnt = 3;

    // 下一步生成小球的数量
    m_nextBallCnt = 3;

    // 小球的种类
    m_ballTypeCnt = m_nextBallCnt + 2;

    // 最少的消除小球的数量
    m_leastDestoyCnt = 5;

    // 矩阵的尺寸
    m_MatrixWidth = 9;
    m_MatrixHeight = 9;

    m_pCtrl = new CControl(this);

    // 创建小球的信号必须绑定在 reset之前
    // 不然接收不到第一次小球创建的信号
    connect(m_pCtrl, SIGNAL(CreatedNewBall(QList < CBall >)),
            this, SLOT(CreatedNewBall(QList < CBall >)));

    m_pCtrl->reset(m_startBallCnt, m_nextBallCnt,
                   m_ballTypeCnt, m_leastDestoyCnt,
                   m_MatrixWidth, m_MatrixHeight);

    ui->Checkerboard->setControl(m_pCtrl);

    // 绑定移动小球的信号
    // 必须在 ui->Checkerboard->setControl(m_pCtrl) 之后
    connect(m_pCtrl, SIGNAL(BallHasMoved(QStack<QPoint>)),
            this, SLOT(BallHasMoved(QStack<QPoint>)));

    // 绑定
    connect(m_pCtrl, SIGNAL(updateScore(int)),
            this, SLOT(updateScore(int)));

    updateScore(0);

}

destroyball::~destroyball()
{
    delete ui;
}


///
/// \brief destroyball::showEvent
/// 每次显示的事件
///
/// \param e
///
void destroyball::showEvent(QShowEvent *e)
{
    ui->btnExit->hide();

    QWidget::showEvent(e);

}

///
/// \brief destroyball::resizeEvent
/// 控件重新排列的事件
///
void destroyball::resizeEvent(QResizeEvent *)
{
    ui->lblScore->setMaximumHeight(this->height() / 10);

   float nextHeight = 1.0 * ui->Checkerboard->height() / m_MatrixHeight;
    float nextWidth = m_nextBallCnt * ui->Checkerboard->width()  / m_MatrixHeight;

    ui->nextInfo->setMaximumHeight(nextHeight);

    ui->nextInfo->setMaximumWidth(nextWidth);
}


///
/// \brief destroyball::BallHasMoved
/// 小球移动后的下一步的操作
///
void destroyball::BallHasMoved(QStack<QPoint> path)
{
    // 移动小球
    ui->Checkerboard->MoveBall(path);

    // 下一步的操作
    if (m_pCtrl->NextStep() == false)
    {
        QMessageBox::question(this, tr("提示"), tr("本局已经结束 是否再来一局"), QMessageBox::Yes | QMessageBox::No, QMessageBox::Yes);

        exit(0);

    }

}

///
/// \brief destroyball::updateScore
/// 更新分数
///
/// \param score
/// 当前的分数
///
void destroyball::updateScore(int score)
{
    QString scoreStr;

    scoreStr.append(tr("当前分数：%1").arg(score));

    ui->lblScore->setText(scoreStr);
}


void destroyball::CreatedNewBall(QList< CBall > newball)
{
    ui->nextInfo->setNextInfoBall(newball);
    ui->nextInfo->update();
}

///
/// \brief destroyball::on_btnRestart_clicked
/// 重新开始
///
void destroyball::on_btnRestart_clicked()
{
    m_pCtrl->reset(m_startBallCnt, m_nextBallCnt,
                   m_ballTypeCnt, m_leastDestoyCnt,
                   m_MatrixWidth, m_MatrixHeight);

    updateScore(0);

}
